package cn.ysym.util;

import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by Administrator on 2016/12/22 0022.
 */
public class HttpUtil {

    public static String SERVICE_URL_BASE = "http://ysym.cn/yunma/scanner/";

    private HttpUtil() {
    }

    public static String genSign(JSONObject params, String sessionKey) {
        Map<String, String> signs = new HashMap<>();
        Iterator<String> keys = params.keys();
        while (keys.hasNext()) {
            String key = keys.next();
            try {
                signs.put(key, params.getString(key));
            } catch (JSONException e) {
            }
        }
        String linkStr = CommonUtil.createLinkString(signs);
        String sign = CommonUtil.md5Digest(linkStr + sessionKey);
        return sign;
    }

    public static String postJson(String url, String jsonStr) throws Exception {
        String encoding = "utf-8";
        URL urlAddr = new URL(SERVICE_URL_BASE + url);
        HttpURLConnection conn = (HttpURLConnection) urlAddr.openConnection();
        try {
            conn.setRequestProperty("User-Agent", "openwave (compatible; MSIE 7.0;)");
            conn.setConnectTimeout(10 * 1000);
            conn.setReadTimeout(180 * 1000);
            conn.setUseCaches(false);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            conn.setRequestProperty("ContentEncoding", encoding);
            Writer writer = new OutputStreamWriter(conn.getOutputStream(),
                    encoding);
            writer.write(jsonStr);
            writer.flush();
            writer.close();

            StringBuilder retVal = new StringBuilder();
            Log.e("conn", String.valueOf(conn.getResponseCode()) );
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                BufferedReader l_reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
                String sCurrentLine;
                while ((sCurrentLine = l_reader.readLine()) != null) {
                    retVal.append(sCurrentLine.trim());
                }
                String retStr = retVal.toString();
                System.out.println("res: " + retStr);
                return retStr;
            }
            return null;
        } catch (Exception e) {
            throw e;
        } finally {
            conn.disconnect();
        }
    }
}
